package com.xsp.eduservice.controller;


import com.alibaba.excel.util.StringUtils;
import com.xsp.eduservice.client.VoClient;
import com.xsp.eduservice.entity.EduVideo;
import com.xsp.eduservice.service.EduVideoService;
import com.xsp.commonutils.R;
import com.xsp.commonutils.servicebase.exceptionhandler.GuLiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-02-11
 */
@RestController
@RequestMapping("/eduservice/video")
public class EduVideoController {
    @Autowired
    EduVideoService eduVideoService;
    @Autowired
    VoClient voClient;

    //通过小节id获取小节信息
    @GetMapping("getVideoInfo/{id}")
    public R getVideoInfo(@PathVariable String id){
        EduVideo videoInfo = eduVideoService.getById(id);
        return R.ok().data("videoInfo",videoInfo);
    }

    //添加小节
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    //修改小节
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.updateById(eduVideo);
        return R.ok();
    }
    //删除小节,并且删除阿里云中的视频
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id){
        //先通过小节id拿到视频id
        EduVideo eduVideo = eduVideoService.getById(id);
        String videoSourceId = eduVideo.getVideoSourceId();
        //通过视频id删除视频
        if (!StringUtils.isEmpty(videoSourceId)){
        //voClient.removeVideo(videoSourceId);
        //测试熔断器(vod宕机时debug看getCode)
        //当vod服务宕机或者超时时，会发生熔断，云端视频不会删除，但是页面中的数据会被删除
            R r = voClient.removeVideo(videoSourceId);
            if (r.getCode()==20001){
                throw new GuLiException(20001,"删除视频失败,熔断器...");
            }

        }
        //最后删除小节
        eduVideoService.removeById(id);
        return R.ok();
    }

    //更新视频id(video_source_id)和视频名字(video_original_name)
    //只修改部分字段的值，使用putmapping
    @PutMapping ("updateSourceIdAndName/{id}")
    public R updateSourceIdAndName(@PathVariable String id){
        eduVideoService.updateSourceIdAndName(id);
        return R.ok();
    }
}

